package vip.youngboy.gateway.route;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;

@Component
public class NacosDynamicRouteProvider implements InitializingBean {

    private static final String ADMIN_DATA_ID = "gateway";

    private static final String ADMIN_GROUP_ID = "gateway";

    @Autowired
    private DynamicRouteService dynamicRouteService;

    public void onRouteChange() {
        try {
            ConfigService configService = NacosFactory.createConfigService("127.0.0.1:8848");
            String content = configService.getConfig(ADMIN_DATA_ID, ADMIN_GROUP_ID, 5000);
            System.out.println(content);
            configService.addListener(ADMIN_DATA_ID, ADMIN_GROUP_ID, new Listener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    RouteDefinition definition = JSON.parseObject(configInfo, RouteDefinition.class);
                    dynamicRouteService.update(definition);
                }

                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
        } catch (NacosException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        onRouteChange();
    }
}
